<template>
    <div v-if="authStore.isAuthenticated" class="member-management-container">
        <h2>Minor Member Management</h2>
        <a-alert v-if="error" type="error">{{ error }}</a-alert>
        <a-spin :spinning="loading">
            <a-table :columns="columns" :data-source="members" bordered>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'actions'">
                        <a-popconfirm title="Are you sure delete this member?" ok-text="Yes" cancel-text="No"
                            @confirm="showConfirm(record.userId)" @cancel="cancel">
                            <a href="#" style="color: red;">Delete</a>
                        </a-popconfirm>
                    </template>
                    <template v-else-if="column.key === 'birthDate'">
                        {{ formatDate(record.birthDate) }}
                    </template>
                </template>
                <template #guardians="{ record }">
                    <a-collapse>
                        <a-collapse-panel header="Click to view details" key="guardians">
                            <div class="guardian-info">
                                <!-- Guardian 1 -->
                                <div class="guardian-item">
                                    <p>Guardian 1 Name: {{ record.guardian1Name }}</p>
                                    <p>Phone: {{ record.guardian1PhoneNumber }}</p>
                                    <p>Address: {{ record.guardian1Address }}</p>
                                </div>
                                <!-- Guardian 2 -->
                                <div class="guardian-item">
                                    <p>Guardian 2 Name: {{ record.guardian2Name }}</p>
                                    <p>Phone: {{ record.guardian2PhoneNumber }}</p>
                                    <p>Address: {{ record.guardian2Address }}</p>
                                </div>
                            </div>
                        </a-collapse-panel>
                    </a-collapse>
                </template>
            </a-table>
        </a-spin>
    </div>
    <a-alert v-else class="no-data" type="warning" show-icon>
        <template #message>
            You must log in/register to manage members.
        </template>
        <template #description>
            Redirecting to the login page in {{ countdown }} seconds...
        </template>
    </a-alert>
    <a-modal v-model:visible="confirmVisible" title="Delete Confirmation" ok-text="Confirm Delete" cancel-text="Cancel" @ok="handleDelete">
        <p>Are you sure you want to delete the information of User ID {{ currentUserId }}?</p>
    </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';
import { Modal } from 'ant-design-vue'; // 或者使用组件式引入
import axios from '../axios';
import dayjs from 'dayjs';

// 定义 Member 接口
interface Member {
    userId: number;
    sruNumber: string;
    address: string;
    birthDate: string;
    phoneNumber: string;
    mobileNumber: string;
    zipCode: string;
    email: string;
    closest: string;
    closestPhoneNumber: string;
    doctor: string;
    doctorPhoneNumber: string;
    knownHealthIssues: string;
}

const authStore = useAuthStore();
const router = useRouter();
const members = ref<Member[]>([]);
const loading = ref(false);
const error = ref('');
const countdown = ref(5);
const confirmVisible = ref(false);
const currentUserId = ref(0);
// 表格列定义
const columns = [
    { title: 'User ID', dataIndex: 'userId', key: 'userId' },
    { title: 'SRU Number', dataIndex: 'sruNumber', key: 'sruNumber' },
    { title: 'Address', dataIndex: 'address', key: 'address' },
    { title: 'Date of Birth', dataIndex: 'birthDate', key: 'birthDate' },
    { title: 'Phone Number', dataIndex: 'phoneNumber', key: 'phoneNumber' },
    { title: 'Mobile Number', dataIndex: 'mobileNumber', key: 'mobileNumber' },
    { title: 'Zip Code', dataIndex: 'zipCode', key: 'zipCode' },
    { title: 'Email', dataIndex: 'email', key: 'email' },
    { title: 'Doctor Name', dataIndex: 'doctor', key: 'doctor' },
    { title: 'Doctor Phone', dataIndex: 'doctorPhoneNumber', key: 'doctorPhoneNumber' },
    { title: 'Known Health Issues', dataIndex: 'knownHealthIssues', key: 'knownHealthIssues' },
    { title: 'Doctor Address', dataIndex: 'doctorAddress', key: 'doctorAddress' },
    {
        title: 'Guardian Information',
        key: 'guardians',
        width: 400,
        slots: { customRender: 'guardians' },
    },
    { title: 'Actions', key: 'actions' },
];

// 格式化日期
const formatDate = (dateString: string) => {
    return dayjs(dateString).format('YYYY-MM-DD');
};

const cancel = (e: MouseEvent) => {
  console.log(e);
};
// 获取会员列表
const fetchMembers = async () => {
    try {
        loading.value = true;
        const res = await axios.get('/minor_members');
        members.value = res.data.data; // 根据 API 响应结构调整
    } catch (err) {
        error.value = 'Failed to obtain member information';
    } finally {
        loading.value = false;
    }
};





const showConfirm = (userId: number) => {
    currentUserId.value = userId;
    confirmVisible.value = true;
};
// 删除会员
const handleDelete = async () => {
    try {
        await axios.delete(`/members/${currentUserId.value}`);
        fetchMembers();
        currentUserId.value = 0;
    } catch (err) {
        error.value = 'Failed to delete member';
    } finally {
        confirmVisible.value = false;
    }
};

// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
    if (!isAuthenticated) {
        const timer = setInterval(() => {
            if (countdown.value > 0) {
                countdown.value--;
            } else {
                clearInterval(timer);
                router.push({ name: 'Auth' });
            }
        }, 1000);
    }
}, { immediate: true });

// 页面加载时获取数据
onMounted(() => {
    if (authStore.isAuthenticated) {
        fetchMembers();
    }
});
</script>

<style scoped>
.member-management-container {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
}

.guardian-info {
  line-height: 1.6;
}

.guardian-item {
  margin-bottom: 16px;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.guardian-item:last-child {
  margin-bottom: 0;
}
</style>